<script lang="ts" setup>
import { ref, computed, onMounted, watch, nextTick } from "vue"
import { ISerach } from "@cop/Icons"
import { getVideoByKeyword } from "@/api/index"
import { formatDate } from "@/util/util"
import { NEmpty } from "naive-ui"
import { videoId, loadding } from "@/hooks/useVideoId"
import { debounce } from "radash"
const input = ref<HTMLDivElement>(null)
const searchResult = ref<HTMLDivElement>(null)
const current = ref<number>(-1)
const searchModel = ref<string>("")
const list = ref<Array<Post>>([])
let inputHeight

onMounted(() => {
  inputHeight = computed(() => {
    return input.value.getBoundingClientRect().height + "px"
  })
})

const getVideo = id => {
  videoId.value = id
  searchResultIsShow.value = false
}

const searchResultIsShow = ref<boolean>(false)

watch(searchResultIsShow, val => {
  if (!val) {
    current.value = -1
  }
})

watch(
  searchModel,
  debounce({ delay: 600 }, val => {
    if (val.trim() != "") {
      getVideoByKeyword(val)
        .then(res => {
          list.value = res.data.videos
          searchResultIsShow.value = true
        })
        .catch(err => {
          list.value = []
          searchResultIsShow.value = true
        })
    } else {
      searchResultIsShow.value = false
    }
  })
)

const inputBlur = () => {
  // searchResultIsShow.value = false
}
const inputFocus = () => {
  if (searchModel.value.trim() != "") {
    searchResultIsShow.value = true
  }
}

const scrollToCurrentElement = () => {
  const currentElement = searchResult.value.children[current.value]
  if (currentElement) {
    currentElement.scrollIntoView({ behavior: "smooth" })
  }
}

const handleKeyDown = (event: KeyboardEvent) => {
  // console.log(event.key)
  if (searchResultIsShow.value) {
    if (event.key === "ArrowUp") {
      // 上方向键按下
      console.log("上方向键按下")
      if (current.value == 0) {
        current.value = list.value.length - 1
        return
      }
      current.value--
      console.log(current.value)
      // if (current.value == -1) return
      scrollToCurrentElement()
    } else if (event.key === "ArrowDown") {
      // 下方向键按下
      if (current.value == list.value.length - 1) {
        current.value = 0
        return
      }
      console.log("下方向键按下")
      current.value++
      console.log(current.value)
      // if (current.value == 0) return
      scrollToCurrentElement()
    } else if (event.key === "Enter") {
      videoId.value = list.value[current.value].id
      searchResultIsShow.value = false
      // openPostDetail(list.value[current.value].id)
    }
  }
}

const computeAnimateDuration = computed(() => (i: number) => i < 6 ? i * 0.5 : 2.5999999999999998)
</script>

<template>
  <div class="searchBox">
    <div class="input" ref="input">
      <input
        v-model="searchModel"
        type="text"
        :style="{ height: inputHeight }"
        @blur="inputBlur"
        @focus="inputFocus"
        @keydown="handleKeyDown"
        placeholder="请输入关键字搜索影视～"
      />
      <div class="suffix">
        <ISerach size="18" color="var(--icon-color)" />
      </div>
    </div>
    <div class="search-result" v-if="searchResultIsShow" ref="searchResult">
      <template v-if="list.length">
        <div
          class="item"
          v-for="(item, i) in list"
          :style="'--t:' + computeAnimateDuration(i + 1) + 's;'"
          :class="{
            'active-item': i == current,
          }"
          @click.stop="getVideo(item.id)"
        >
          <div class="img">
            <img :src="item.cover" alt="" />
          </div>
          <div class="info">
            <div class="title">{{ item.name }}</div>
            <div class="author">
              {{ item.uptodate }}
              <span style="margin-left: 10px">{{ item.premiere }}</span>
            </div>
          </div>
        </div>
      </template>
      <n-empty description="没有搜索到呢～" style="height: 100%; justify-content: center" v-else>
      </n-empty>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@keyframes fadeInBottom {
  0% {
    opacity: 0;
    filter: blur(3px);
    transform: translateY(70px);
  }
  100% {
    opacity: 1;
    filter: blur(0);
    transform: translateY(0);
  }
}
.searchBox {
  height: 55%;
  margin-left: 20px;
  position: relative;
  @media only screen and (max-width: 767px) {
    /* 在宽度小于等于 767px 的设备上应用以下样式 */
    width: 60vw !important;
  }

  /* 桌面设备样式 */
  @media only screen and (min-width: 1024px) {
    /* 在宽度大于等于 1024px 的设备上应用以下样式 */
    width: 400px;
  }
  .input {
    width: 100%;
    height: 100%;
    border-radius: 30px;
    background-color: var(--search-bg);
    transition: all 0.3s var(--n-bezier);
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 15px;
    position: relative;
    z-index: 99;
    input {
      width: 95%;
      border: none;
      outline: none;
      background-color: var(--search-bg);
      caret-color: var(--themeColor);
      color: var(--TextColor);
      transition: all 0.3s var(--n-bezier);
      font-size: 14px;
    }
    .suffix {
      flex: 1;
      @include center;
    }
  }
  .search-result {
    width: 100%;
    height: 50vh;
    background: var(--search-result-bg);
    position: absolute;
    bottom: -50.5vh;
    left: 0;
    z-index: 99;
    box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
    border-radius: 10px;
    backdrop-filter: blur(10px);
    box-sizing: border-box;
    padding: 10px;
    overflow-y: scroll;
    &::-webkit-scrollbar,
    &::-webkit-scrollbar-track-piece {
      background-color: transparent;
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 3px;
      background-color: var(--search-result-scroll-bg) !important;
      background-image: none;
    }

    &::-webkit-scrollbar {
      width: 7px;
      height: 6px;
    }
    .active-item {
      background-color: var(--side-menu-active-color);
    }
    .item {
      display: flex;
      align-items: center;
      gap: 10px;
      box-sizing: border-box;
      padding: 5px 10px 5px 10px;
      border-radius: 4px;
      cursor: pointer;
      margin-bottom: 5px;
      transition: var(--basic-transition);
      animation: fadeInBottom var(--t) ease-in-out;
      &:hover {
        background-color: var(--side-menu-active-color);
      }
      .img {
        width: 40px;
        height: 40px;
        flex-shrink: 0;

        img {
          height: 100%;
          width: 100%;
          border-radius: 4px;
        }
      }
      .info {
        flex: 1;
        .title {
          color: var(--TextColor);
          font-size: 16px;
          word-break: break-all;
          overflow: hidden;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }
        .author {
          color: var(--TextColor);
          font-size: 14px;
        }
      }
    }
  }
}
</style>
